package com.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.MmallCategory;
import com.mall.entity.MmallOrder;
import com.mall.entity.MmallOrderItem;
import com.mall.entity.vo.OrderItemVo;
import com.mall.entity.vo.OrderQuery;
import com.mall.service.MmallCategoryService;
import com.mall.service.MmallOrderItemService;
import com.mall.service.MmallOrderService;
import com.mall.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ppmall
 * @since 2021-09-19
 */
@CrossOrigin
@RestController
@RequestMapping("/mall/order")
public class MmallOrderController {

    @Autowired
    MmallOrderService orderService;

    @Autowired
    MmallOrderItemService orderItemService;

    @Autowired
    MmallCategoryService categoryService;

    @PostMapping("/orders/{cur}/{limit}")
    public R getOrders(@PathVariable("cur") long cur,
                        @PathVariable("limit") long limit,
                        @RequestBody OrderQuery orderQuery){
        Page<MmallOrder> page = new Page<>(cur, limit);
        QueryWrapper<MmallOrder> wrapper = new QueryWrapper<>();

        Long orderNo = orderQuery.getOrderNo();
        Integer userId = orderQuery.getUserId();

        if(orderNo != null) {
            wrapper.eq("order_no", orderNo);
        }

        if(userId != null) {
            wrapper.eq("user_id", userId);
        }

        orderService.page(page, wrapper);

        long total = page.getTotal();
        List<MmallOrder> records = page.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @GetMapping("/order")
    public R getOrderById(Integer id){
        MmallOrder order = orderService.getById(id);
        return R.ok().data("order", order);
    }

    @PutMapping("/order")
    public R updateOrderById(@RequestBody MmallOrder order) {
        return orderService.updateById(order) ? R.ok() : R.error();
    }

    @PostMapping("/order")
    public R addOrder(@RequestBody MmallOrder order) {
        System.out.println(order);
        return orderService.save(order) ? R.ok() : R.error();
    }

    @DeleteMapping("/order/{id}")
    public R deleteOrderById(@PathVariable("id") Integer id){
        return orderService.removeById(id) ? R.ok() : R.error();
    }

    @GetMapping("/detail")
    public R getOrderDetail(Integer id) {
        MmallOrder order = orderService.getById(id);
        OrderItemVo detail = new OrderItemVo();
        BeanUtils.copyProperties(order, detail);
        List<MmallOrderItem> orderItems = orderItemService.getOrderItemByOrderNo(order.getOrderNo());
        detail.setOrderItems(orderItems);
        return R.ok().data("detail", detail);
    }

    @GetMapping("/earn_in_7")
    public R getEarnInSeven(Integer day_num) {
        long one_day = 1000 * 3600 * 24;
        long current = System.currentTimeMillis();
        long day_begin = current / one_day * one_day - TimeZone.getDefault().getRawOffset();
        long day_end = day_begin + one_day - 1;//今天23点59分59秒的毫秒数

        List<String> days = new ArrayList<>();
        List<BigDecimal> totals = new ArrayList<>();

        for(int i = day_num - 1; i >= 0; i--) {
            Date begin = new Date(day_begin - i * one_day);
            Date end = new Date(day_end - i * one_day);
            QueryWrapper<MmallOrder> wrapper = new QueryWrapper<>();
            wrapper.ge("payment_time", begin);
            wrapper.le("payment_time", end);
            int[] array = {20, 40, 50, 60};
            wrapper.in("status", CollectionUtils.arrayToList(array));
            List<MmallOrder> orders = orderService.list(wrapper);

            String day = (begin.getYear() + 1900) + "." + (begin.getMonth() + 1) + "." + begin.getDate();
            BigDecimal total = BigDecimal.valueOf(0);

            for(MmallOrder order: orders) {
                total = total.add(order.getPayment());
            }

            days.add(day);
            totals.add(total);
        }

        return R.ok().data("days", days).data("totals", totals);
    }

    @GetMapping("category_ratio")
    public R getCategoryRatio(Integer day_num) {
        QueryWrapper<MmallCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<MmallCategory> categories = categoryService.list(wrapper);

        long one_day = 1000 * 3600 * 24;
        long current = System.currentTimeMillis();
        long day_begin = current / one_day * one_day - TimeZone.getDefault().getRawOffset();
        long day_end = day_begin + one_day - 1;//今天23点59分59秒的毫秒数

        long begin = day_begin - one_day * day_num;
        long end = day_end;

        List<String> categoryNames = new ArrayList<>();
        List<BigDecimal> categoryPayments = new ArrayList<>();

        BigDecimal total = new BigDecimal(0);

        for(MmallCategory category: categories) {
            categoryNames.add(category.getName());
            BigDecimal totalPayment = orderService.getTotalPaymentByCategoryId(category.getId(), new Date(begin), new Date(end));
            if(totalPayment == null) {
                totalPayment = new BigDecimal(0);
            }
            categoryPayments.add(totalPayment);
            total = total.add(totalPayment);
        }

        return R.ok().data("names", categoryNames).data("payments", categoryPayments).data("total", total);
    }


}

